<template>
  <van-form @submit="onSubmit">
  <van-field
    v-model="addressData.name"
    name="用户名"
    label="用户名"
    placeholder="用户名"
    :rules="[{ required: true, message: '请填写用户名' }]"
  />
  <van-field
    v-model="addressData.addressinfo"
    name="地址信息"
    label="地址信息"
    :rules="[{ required: true, message: '请填写地址信息' }]"
  />
   <van-field
    v-model="addressData.phone"
    name="手机号"
    label="手机号"
    :rules="[{ required: true, message: '请填写手机号' }]"
  />
  <div style="margin: 16px;" v-if="type === 'edit'">
    <van-button round block type="danger" native-type="button" @click="handleRemore">删除</van-button>
  </div>
  <div style="margin: 16px;">
    <van-button round block type="info" native-type="submit">{{text}}</van-button>
  </div>
</van-form>
</template>

<script>
import {addList,getListData,updateListData,remoteListtData} from "@/api"
import {loading,clearToast} from "@/utils/loading"

export default {
    data(){
        return {
           addressData:{
               name:"",
               addressinfo:"",
               phone:""
           }
        }
    },
    computed:{
        type(){
            return this.$route.params.type;
        },
        text(){
            return this.type === 'edit' ? "编辑" : "新增"
        }
    },
    mounted(){
        // 新增还是编辑
        if(this.type === 'edit'){
            const { id } = this.$route.query;
            loading();
            if( id === undefined ) {
                this.$dialog.alert({
                    message: '参数不合法点击回到首页',
                }).then(()=>{
                    this.$router.replace('/')
                });
                return;
            }
            // 参数正确获取地址数据 数据回显
            this.getListData(id);
        }
    },  
    methods:{
        onSubmit(){
            if(this.type === 'add'){
                addList(this.addressData).then(res => {
                    this.$router.push('/')
                })
            } else {
                updateListData(this.addressData.id,{
                    ...this.addressData
                }).then(res => {
                    this.$router.push('/')
                })
            }
        },
        getListData(id){
           getListData(id).then(res => {
               this.addressData = res.data;
               clearToast();
           })
        },
        handleRemore(){
            remoteListtData(this.addressData.id).then(res =>{
                 this.$router.replace('/')
            })
        }
    }
}
</script>

<style>

</style>